#include <stdint.h>

#include "lsv.h"
#include "lsv_conf.h"
#include "lsv_bitmap.h"

#define M1 1048576

int read_bitmap_chunk(int chunk_id) {
        int i, ret, fd;
        char name[256];
        char buf[M1];
        lsv_bitmap_unit_t *unit;
        uint32_t lba;
        uint32_t old_chunk_id;
        uint32_t old_chunk_off;

        memset(buf, 0, M1);

        sprintf(name, "raw.1026.%d.dump", chunk_id);
        fd = open(name, 0);
        printf("open file %s %d\n", name, fd);

        ret = read(fd, buf, M1);
        printf("ret = %d\n", ret);
        printf("\n\n");

        unit = (lsv_bitmap_unit_t *)buf;
        if (unit->chunk_id) {
                // printf("\t%u %u\n", unit->chunk_id, unit->chunk_off);
        }

        old_chunk_id = 0;
        old_chunk_off = 0;
        for (i=0; i<M1/8; i+=8) {
                unit = (lsv_bitmap_unit_t *)(buf+i);
                if (unit->chunk_id) {
                        if (old_chunk_id == 0 || old_chunk_id != unit->chunk_id) {
                                old_chunk_id = unit->chunk_id;
                                old_chunk_off = 0;
                        }
                        //printf("%d %p %u %u\n", i, buf+i, unit->chunk_id, unit->chunk_off);
                        if (unit->chunk_off - old_chunk_off != 4096) {
                                //printf("\terror: %u %u %u\n", old_chunk_id, old_chunk_off, unit->chunk_off);
                        }
                        old_chunk_off = unit->chunk_off;
                }
        }

        // merge
        fd = open("merge.img", O_CREAT|O_APPEND);
        printf("open merge.img %d\n", fd);
        for (i=0; i<M1/8; i+=8) {
                unit = (lsv_bitmap_unit_t *)(buf+i);
                printf("chunk_id %u\n", unit->chunk_id);
                if (unit->chunk_id) {

                }
        }
        return 0;
}

int main(int argc, char *argv[]) {
        int i, ret, fd;
        struct lsv_chunk_bitmap chunk;
        char buf[M1];
        lsv_bitmap_header_t *header;

        memset(buf, 0, M1);

        for (i=0; i < argc; i++) {
                printf("arg %d %s\n", i, argv[i]);
        }

        fd = open(argv[1], 0);
        if (fd < 0) {
                printf("error\n");
        }

        ret = read(fd, buf, M1);
        printf("ret = %d\n", ret);

        header = (lsv_bitmap_header_t *)buf;

        printf("\n\n");
        printf("sign %s\n", header->sign);
        for (i=0; i < 10; ++i) {
                chunk = header->chunk_map[i];
                printf("child chunk %d\n", chunk.chunk_id);
                if (chunk.chunk_id) {
                        read_bitmap_chunk(chunk.chunk_id);
                }
        }


        return 0;
}
